package com.fjh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjh.constant.CategoryConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.domain.Category;
import com.fjh.mapper.CategoryMapper;
import com.fjh.service.CategoryService;
import org.springframework.util.ObjectUtils;

@Service
@Slf4j
@CacheConfig(cacheNames = "com.fjh.service.impl.CategoryServiceImpl.")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     *查询商品分类
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_PREFIX)
    public List<Category> list() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                    .orderByDesc(Category::getSeq)
        );
    }

    /**
     * 新增商品
     * @param category
     * @return
     * evict为删除redis缓存中的key
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = CategoryConstant.CATEGORY_PREFIX),
                    @CacheEvict(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
            }
    )
    public boolean save(Category category) {
        log.info("新增分类{}", JSON.toJSONString(category));
        category.setRecTime(new Date());
        category.setUpdateTime(new Date());
        category.setShopId(1L);
        Long parentId = category.getParentId();
        if (parentId == null || parentId.equals(0L)){
            //说明新增了一个根级分类
            parentId = 0L;
            category.setGrade(1);
        }else {
            //判断数据库有没有父分类
            Category parent = categoryMapper.selectById(parentId);
            if (!ObjectUtils.isEmpty(parent)){
                throw new IllegalArgumentException("新增的父分类不存在");
            }
            category.setGrade(2);
        }
        //新增
        return categoryMapper.insert(category)>0;
    }

    /**
     * 查询商品的父分类
     * @return
     */
    @Override
    public List<Category> loadParentCategory() {
        return null;
    }

}
